package cbfg.http.demo

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import cbfg.http.subscribe.Disposable

/**
 * @author:  Tom Hawk
 * 添加时间: 2020/9/22 16:30
 * 功能描述:
 */
object LifecycleUtils {
    fun bindUntil(
        lifecycle: Lifecycle,
        endEvent: Lifecycle.Event,
        disposable: Disposable
    ) {
        lifecycle.addObserver(object : LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            fun onPause() {
                checkDispose(Lifecycle.Event.ON_PAUSE)
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            fun onStop() {
                checkDispose(Lifecycle.Event.ON_STOP)
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            fun onDestroy() {
                checkDispose(Lifecycle.Event.ON_DESTROY)
            }

            private fun checkDispose(event: Lifecycle.Event) {
                if (event == endEvent) {
                    lifecycle.removeObserver(this)
                    disposable.dispose()
                }
            }
        })
    }
}